package cn.tedu.fengyuback.personal.service.impl;

import cn.tedu.fengyuback.base.constent.Constant;
import cn.tedu.fengyuback.personal.mapper.LikesMapper;
import cn.tedu.fengyuback.personal.mapper.PersonalMapper;
import cn.tedu.fengyuback.personal.pojo.dto.ArticlesQuery;
import cn.tedu.fengyuback.personal.pojo.dto.FavoritesQuery;
import cn.tedu.fengyuback.personal.pojo.dto.LikesQuery;
import cn.tedu.fengyuback.personal.pojo.vo.ArticlesVO;
import cn.tedu.fengyuback.personal.pojo.vo.FavoritesVO;
import cn.tedu.fengyuback.personal.pojo.vo.LikesVO;
import cn.tedu.fengyuback.personal.service.LikesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class LikesServiceImpl implements LikesService {
    @Autowired
    LikesMapper likesMapper;
    @Autowired
    PersonalMapper personalMapper;

    /**
     * 查询点赞文章
     * @param likesQuery
     * @return
     */
    @Override
    public List<ArticlesVO> selectLike(LikesQuery likesQuery) {
        log.debug("开始处理查询点赞文章的业务");
        //查询点赞文章
        List<LikesVO> likesVOS = likesMapper.selectLike(likesQuery);
        //设置集合保存查询点赞文章的参数
        ArticlesQuery articlesQuery = new ArticlesQuery();
        //设置集合保存点赞文章的具体内容
        List<ArticlesVO> articlesVOS = new ArrayList<>();
        for (LikesVO likesVO : likesVOS){
            log.debug("likesVO={}",likesVO);
           articlesVOS.add(queryLike(articlesQuery,likesVO));
        }
//        log.debug("查询到的文章信息为：{}",articlesVOS);
        return articlesVOS;
    }

    /**
     * 查询点赞文章具体内容
     * @param articlesQuery
     * @param likesVO
     */
    private ArticlesVO queryLike(ArticlesQuery articlesQuery, LikesVO likesVO) {
        articlesQuery.setId(likesVO.getArticleId());
        ArticlesVO articlesVO = personalMapper.selectByIdArticle(articlesQuery).get(0);
        //设置点赞表id、点赞状态
        articlesVO.setLikesId(likesVO.getId());
        articlesVO.setLikesStatus(Constant.ARTICLE_LIKE_FAVORITES);
        queryFavorites(likesVO,articlesVO);
        return articlesVO;
    }

    /**
     * 查询点赞页面被收藏的文章
     * @param articlesVO
     * @param likesVO
     * @return
     */
    private void queryFavorites(LikesVO likesVO, ArticlesVO articlesVO) {
        FavoritesQuery favoritesQuery = new FavoritesQuery();
        favoritesQuery.setArticleId(likesVO.getArticleId());
        FavoritesVO favoritesVO = personalMapper.selectFavorites(favoritesQuery);
        if (favoritesVO != null){
            articlesVO.setFavoritesId(favoritesVO.getId());
            articlesVO.setFavoritesStatus(Constant.ARTICLE_LIKE_FAVORITES);
        }else {
            articlesVO.setFavoritesStatus(Constant.NOT_ARTICLE_LIKE_FAVORITES);
        }
    }
}
